package com.xiang.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static  DataSource ds;
    static{
        try {
            //创建Properties对象
            Properties prop = new Properties();
            //根据当前类加载器去加载配置文件(推荐)
            InputStream in = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            //加载druid.properties配置文件
            prop.load(in);
            //创建数据源(数据源工厂提供数据源)
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
      获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }

    //获取连接
    public static  Connection getConnection(){
        try {
            Connection conn = ds.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }

    //释放资源
    public static void closeAll(ResultSet rs, PreparedStatement pstm, Connection conn){
        //判断
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(pstm != null){
            try {
                pstm.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }


}
